package db

import (
	"fmt"
	"reflect"
	"svr/src/xutil"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

const RdsDur = time.Hour * 3000

var sql *gorm.DB

func createMySql() (*gorm.DB, error) {
	host := "127.0.0.1"
	port := 3306
	user := "root"
	pass := "qqqq1111"
	dbname := "test"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		user,
		pass,
		host,
		port,
		dbname)
	fmt.Println("dsn: ", dsn)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return nil, err
	}
	db.AutoMigrate(
		&Account{},
	)
	return db, nil
}

func InitMySql() *gorm.DB {
	var err error
	sql, err = createMySql()
	if xutil.CheckErr(err) {
		return nil
	}
	return sql
}

func GetMySql() *gorm.DB {
	if sql == nil {
		return InitMySql()
	}
	return sql
}

// func LockMySqlSaveKey(obj interface{}, id interface{}) (string, string, error) {
// 	k := GetRedisKey(GetTypeName(obj), id)
// 	return LockKey(k)
// }

func GetTypeName(obj interface{}) string {
	if obj == nil {
		return ""
	}
	// 检查传入的参数是否为指针类型
	val := reflect.ValueOf(obj)
	if val.Kind() != reflect.Ptr { //不是指针直接返回名字
		return val.Type().Name()
	}
	//是指针返回指向元素的类型名字
	return val.Elem().Type().Name()
}

type DbModel struct {
	Id        uint64    `gorm:"primarykey;auto_increment" json:"id"`
	CreatedAt time.Time `json:"create"`
	UpdatedAt time.Time `json:"update"`
}
type Account struct {
	DbModel
	Name     string `gorm:"unique" json:"name"`
	Password string `json:"pwd"`
}
